package com.gcloud.dashboard;

import java.net.URI;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;

import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.example.gcode.*;
import com.example.gcode.Archivos;
import com.example.gcode.R.drawable;
import com.gcloud.dropbox.DeleteDropBoxFileActivity;
import com.gcloud.dropbox.DownloadDropBoxFileActivity;
import com.gcloud.dropbox.UploadDropBoxFileActivity;
import com.gcloud.dto.GCloudFile;
import com.gcloud.googledrive.DeleteGoogleFileActivity;
import com.gcloud.googledrive.DownloadGoogleFileActivity;
import com.gcloud.googledrive.UploadGoogleFileActivity;
import com.gcloud.persistance.SQLiteHandler;
import com.utils.Constants;
import com.utils.Message;

public class Fotos extends ListActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fotos_layout);
		registerForContextMenu(getListView());
		loadContent();
		listFiles();
	}

	ArrayList<GCloudFile> list = new ArrayList<GCloudFile>();

	private void loadContent() {
		SQLiteHandler sqliteHandler = new SQLiteHandler(Fotos.this,
				Constants.GCLOUD, null, Constants.DB_VERSION);

		try {
			list = sqliteHandler
					.getFileList(
							"MIMETYPE = ? or MIMETYPE = ? or MIMETYPE = ? or MIMETYPE = ?",
							new String[] { Constants.ajpg, Constants.apng,
									Constants.agif, Constants.abmp });
		} catch (SQLException e) {
			Log.d("Fotos: ", "error: " + e.getMessage());
			showToast("An error occur while query photography files");
			return;
		}
		// if(list!=null && !list.isEmpty()){
		// for (GCloudFile gCloudFile : list) {
		// HashMap<String, String> map = new HashMap<String, String>();
		// map.put(TAG_NOMBRE, gCloudFile.getName());
		// map.put(TAG_FILE_ID, gCloudFile.getKey());
		// map.put(TAG_DESCRIPTION, gCloudFile.getDescription());
		// map.put(TAG_ACCOUNT, gCloudFile.getAccount());
		// lista.add(map);
		// }
		// }

	}

	// ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String,
	// String>>();
	// private static final String TAG_NOMBRE = "TAG_NOMBRE";
	// private static final String TAG_FILE_ID = "TAG_FILE_ID";
	// private static final String TAG_DESCRIPTION = "TAG_DESCRIPTION";
	// private static final String TAG_ACCOUNT = "TAG_ACCOUNT";

	private void listFiles() {

		// for (int i = 0; i < 8; i++) {
		// HashMap<String, String> map = new HashMap<String, String>();
		//
		// map.put(TAG_NOMBRE, "prueba" + i);
		// map.put(TAG_FILE_ID, "KEY: " + i);
		// map.put(TAG_DESCRIPTION, "DESCRIPTION FILE: File number " + i);
		// map.put(TAG_ACCOUNT, "GMAIL OR DROPBOX its something");
		// lista.add(map);
		// }

		ArrayAdapter<GCloudFile> photoAdapter = new GCloudPhotoAdapter();
		// GridView gridView=(GridView)findViewById(R.id.gallery);
		/*
		 * ListAdapter adapter = new SimpleAdapter(Fotos.this, lista,
		 * R.layout.archivos_list_item, new String[] { TAG_NOMBRE, TAG_FILE_ID,
		 * TAG_DESCRIPTION, TAG_ACCOUNT }, new int[] { R.id.list_nombre,
		 * R.id.list_key, R.id.list_service, R.id.list_account });
		 */
		setListAdapter(photoAdapter);

	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	private class GCloudPhotoAdapter extends ArrayAdapter<GCloudFile> {
		public GCloudPhotoAdapter() {
			super(Fotos.this, R.layout.fotos_layout, list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View viewItem = convertView;
			if (viewItem == null) {
				viewItem = getLayoutInflater().inflate(
						R.layout.archivos_list_item, parent, false);
			}
			// GCloudFile currentFile=list.get(position);
			// ImageView photo=(ImageView)viewItem.findViewById(R.id.photoItem);
			// //photo.setImageResource(currentFile.getFileTypeIcon());
			// //Bitmap
			// bitmap=BitmapFactory.decodeFile("http://images2.fanpop.com/image/photos/13800000/farrari-sports-cars-13821367-1280-960.jpg");
			// photo.setImageURI(Uri.parse("http://images2.fanpop.com/image/photos/13800000/farrari-sports-cars-13821367-1280-960.jpg"));
			// photo.setScaleType(ImageView.ScaleType.FIT_CENTER);
			// photo.setPadding(8, 8, 8, 8);
			//
			// TextView
			// description=(TextView)viewItem.findViewById(R.id.photoDesc);
			// description.setText(currentFile.getName());

			GCloudFile currentFile = list.get(position);
			ImageView imageFileType = (ImageView) viewItem
					.findViewById(R.id.img_fileType);
			imageFileType.setImageResource(currentFile.getFileTypeIcon());
			ImageView imageService = (ImageView) viewItem
					.findViewById(R.id.img_servicio);
			imageService.setImageResource(currentFile.getServiceIcon());
			TextView textViewName = (TextView) viewItem
					.findViewById(R.id.list_nombre);
			textViewName.setText(currentFile.getName());
			TextView textViewService = (TextView) viewItem
					.findViewById(R.id.list_service);
			textViewService.setText(currentFile.getSize() + " Bytes");
			return viewItem;
		}

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.contextmenu, menu);
		Log.i("este tag", " si furula");
	}

	private SQLiteHandler sqliteHandler = new SQLiteHandler(Fotos.this,
			Constants.GCLOUD, null, Constants.DB_VERSION);

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		GCloudFile fileSelected = list.get((int) info.id);
		switch (item.getItemId()) {
		case R.id.menu_bookmark:// Favorite
			int favoriteRate = fileSelected.getFavoriteRate();
			favoriteRate += 1;
			sqliteHandler.checkAsFavorite(fileSelected.getKey(), favoriteRate);
			showToast(MessageFormat.format(Message.IS_NEW_FAVORITE,
					fileSelected.getName()));
			return true;
		case R.id.menu_search:// Drop
			if (fileSelected.getService().equals(Constants.GOOGLE)) {
				Intent deleteIntent = new Intent(getApplicationContext(),
						DeleteGoogleFileActivity.class);
				deleteIntent
						.putExtra(Constants.FILE_KEY, fileSelected.getKey());
				startActivity(deleteIntent);
			} else {
				Intent deleteDropBoxFile = new Intent(getApplicationContext(),
						DeleteDropBoxFileActivity.class);
				deleteDropBoxFile.putExtra(Constants.FILE_URL, fileSelected
						.getUrl());
				startActivity(deleteDropBoxFile);
			}
			showToast(MessageFormat.format(Message.FILE_DELETED,
					fileSelected.getName()));
			return true;
		case R.id.menu_save:// Download
			Log.i("menu SAVE", fileSelected.getName());
			if (fileSelected.getService().equals(Constants.DROPBOX)) {
				Log.i("Archivos open file: ",
						"DropBox file: " + fileSelected.getUrl());
				Intent intent = new Intent(getApplicationContext(),
						DownloadDropBoxFileActivity.class);
				intent.putExtra(Constants.FILE_URL, fileSelected.getUrl());
				intent.putExtra(Constants.FILE_NAME, fileSelected.getName());
				intent.putExtra(Constants.FILE_ACCOUNT,
						fileSelected.getAccount());
				startActivity(intent);
			} else {
				// TODO send to download file from google drive
				Log.i("Archivos open file: ", "GoogleDrive file");
				Intent intent = new Intent(getApplicationContext(),
						DownloadGoogleFileActivity.class);
				intent.putExtra(Constants.FILE_KEY, fileSelected.getKey());
				intent.putExtra(Constants.FILE_URL, fileSelected.getUrl());
				intent.putExtra(Constants.FILE_ACCOUNT,
						fileSelected.getAccount());
				intent.putExtra(Constants.FILE_NAME, fileSelected.getName());
				intent.putExtra(Constants.FILE_MIMETYPE,
						fileSelected.getMimeType());
				startActivity(intent);
			}
			return true;
			// showToast("menu save=desc: " + fileSelected.getName());
		case R.id.menu_upload:
			if (fileSelected.getService().equals(Constants.GOOGLE)) {
				Log.i("here", "google drive");
				Intent intentGF = new Intent(Fotos.this,
						UploadGoogleFileActivity.class);
				startActivity(intentGF);
			} else {
				Log.i("here", "dropbox");
				Intent intentDF = new Intent(Fotos.this,
						UploadDropBoxFileActivity.class);
				startActivity(intentDF);
			}
			return true;
			// actionIntent = new Intent(Archivos.this,
			// DownloadGoogleFileActivity.class);
			// actionIntent.putExtra(Constants.FILE_KEY, lista.get((int)
			// info.id)
			// .get(TAG_FILE_ID));
			// startActivity(actionIntent);
		default:
			return super.onContextItemSelected(item);
		}

	}

	private String fileClicked = "";

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		GCloudFile gFile = list.get(position);
		String item = gFile.getKey();// lista.get(position).get(TAG_FILE_ID);
		boolean isDirectory = gFile.isDirectory();
		// GCloudUtil.equals("true", lista.get(position)
		// .get(TAG_IS_DIRECT), false);
		// SQLiteHandler sqliteHandler = new SQLiteHandler(Archivos.this,
		// Constants.GCLOUD, null, Constants.DB_VERSION);
		String mes = "Item: " + item + " : Is Directory: " + isDirectory;
		Log.i("Archivos: ", mes);
		//showToast(mes);
		// sqliteHandler.getFile(item);
		if (item.equalsIgnoreCase(fileClicked)) {
			Log.i("Fotos", fileClicked);
			if (gFile.getService().equals(Constants.DROPBOX)) {
				// TODO send to download file from dropbox
				Log.i("Archivos open file: ", "DropBox file");
				Intent intent = new Intent(getApplicationContext(),
						DownloadDropBoxFileActivity.class);
				intent.putExtra(Constants.FILE_URL, gFile.getUrl());				
				intent.putExtra(Constants.FILE_NAME, gFile.getName());
				intent.putExtra(Constants.FILE_ACCOUNT, gFile.getAccount());
				fileClicked = "";
				startActivity(intent);
			} else if (gFile.getService().equals(Constants.GOOGLE)) {
				// TODO send to download file from google drive
				Log.i("Archivos open file: ", "GoogleDrive file");
				Intent intent = new Intent(getApplicationContext(),
						DownloadGoogleFileActivity.class);
				intent.putExtra(Constants.FILE_KEY, gFile.getKey());
				intent.putExtra(Constants.FILE_URL, gFile.getUrl());
				intent.putExtra(Constants.FILE_ACCOUNT, gFile.getAccount());
				intent.putExtra(Constants.FILE_NAME, gFile.getName());
				intent.putExtra(Constants.FILE_MIMETYPE, gFile.getMimeType());
				fileClicked = "";
				startActivity(intent);
			}			
		} //else {
			fileClicked = item;
			Log.i("FFotos; ",fileClicked);
		//}

	}

	// --------------back up---------------------
	/*
	 * @Override public void onCreate(Bundle savedInstanceState){
	 * super.onCreate(savedInstanceState);
	 * setContentView(R.layout.fotos_layout); loadContent(); listFiles(); }
	 * private void loadContent(){ SQLiteHandler sqliteHandler=new
	 * SQLiteHandler(Fotos.this, Constants.GCLOUD, null, Constants.DB_VERSION);
	 * ArrayList<GCloudFile> list=new ArrayList<GCloudFile>(); try {
	 * list=sqliteHandler.getFileList("MIMETYPE = ?", new
	 * String[]{"image/jpg"}); } catch (SQLException e) {
	 * Log.d("Fotos: ","error: "+e.getMessage());
	 * showToast("An error occur while query photography files"); return; }
	 * if(list!=null && !list.isEmpty()){ for (GCloudFile gCloudFile : list) {
	 * HashMap<String, String> map = new HashMap<String, String>();
	 * map.put(TAG_NOMBRE, gCloudFile.getName()); map.put(TAG_FILE_ID,
	 * gCloudFile.getKey()); map.put(TAG_DESCRIPTION,
	 * gCloudFile.getDescription()); map.put(TAG_ACCOUNT,
	 * gCloudFile.getAccount()); lista.add(map); } }
	 * 
	 * }
	 * 
	 * 
	 * ArrayList<HashMap<String, String>> lista = new ArrayList<HashMap<String,
	 * String>>(); private static final String TAG_NOMBRE = "TAG_NOMBRE";
	 * private static final String TAG_FILE_ID = "TAG_FILE_ID"; private static
	 * final String TAG_DESCRIPTION = "TAG_DESCRIPTION"; private static final
	 * String TAG_ACCOUNT = "TAG_ACCOUNT";
	 * 
	 * private void listFiles() {
	 * 
	 * // for (int i = 0; i < 8; i++) { // HashMap<String, String> map = new
	 * HashMap<String, String>(); // // map.put(TAG_NOMBRE, "prueba" + i); //
	 * map.put(TAG_FILE_ID, "KEY: " + i); // map.put(TAG_DESCRIPTION,
	 * "DESCRIPTION FILE: File number " + i); // map.put(TAG_ACCOUNT,
	 * "GMAIL OR DROPBOX its something"); // lista.add(map); // } ListAdapter
	 * adapter = new SimpleAdapter(Fotos.this, lista,
	 * R.layout.archivos_list_item, new String[] { TAG_NOMBRE, TAG_FILE_ID,
	 * TAG_DESCRIPTION, TAG_ACCOUNT }, new int[] { R.id.list_nombre,
	 * R.id.list_key, R.id.list_service, R.id.list_account });
	 * setListAdapter(adapter);
	 * 
	 * }
	 * 
	 * public void showToast(final String toast) { runOnUiThread(new Runnable()
	 * {
	 * 
	 * @Override public void run() { Toast.makeText(getApplicationContext(),
	 * toast, Toast.LENGTH_SHORT).show(); } }); }
	 */

}
